#pragma once

#include <common.h>
#include <windows.h>
#include <stdbool.h>

#define HOSTEL_MANAGER_HOME_DIR "D:/.hostel-manager/"

/* return true if file not exist
 */
HM_private
bool crt_file_if_not_exist(char const*const filepath) {
    DWORD attrs = GetFileAttributesA(filepath);
    HANDLE file_handle;
    if (attrs == INVALID_FILE_ATTRIBUTES || attrs & FILE_ATTRIBUTE_DIRECTORY) { // file not exist
        file_handle = CreateFileA(filepath, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);

        if (file_handle == INVALID_HANDLE_VALUE) {
            HM_throw(InternalError, "Failed to create config file");
        }
        CloseHandle(file_handle);
        return true;
    }
    return false;
}

/* return true if dir not exist
 */
HM_private
bool crt_hostel_home_dir_if_not_exist(void) {
    if (GetFileAttributesA(HOSTEL_MANAGER_HOME_DIR) == INVALID_FILE_ATTRIBUTES) {
        if (!CreateDirectoryA(HOSTEL_MANAGER_HOME_DIR, NULL)) {
            HM_throw(CreateDirError, "Failed to create directory");
        }
        return true;
    }
    return false;
}

/* @return:
 *   1: \n
 *   0: EOF
 */
HM_private
int read_line(FILE *fp, char *line_buf, size_t line_size) {
    size_t index = 0;
    char chr = 0;
    while (true) {
        chr = fgetc(fp);
        if (chr == EOF) {
            return 0;
        } else if (chr == '\n') {
            return 1;
        }
        if (index >= line_size - 1) {
            HM_throw(InternalError, "index out of range");
        }
        line_buf[index++] = chr;
    }
}
